package com.onlineMIS.ORM.DAO.headQ.inventory;


import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.onlineMIS.ORM.DAO.BaseDAO;
import com.onlineMIS.ORM.entity.chainS.inventoryFlow.ChainInOutStock;
import com.onlineMIS.ORM.entity.headQ.inventory.HeadQInventoryStock;
import com.onlineMIS.common.Common_util;


@Repository
public class HeadQInventoryStockDAOImpl extends BaseDAO<HeadQInventoryStock> {
//      public HeadQInventoryStock getInventoryStock(int storeId, int pbId){
//  		DetachedCriteria criteria = DetachedCriteria.forClass(HeadQInventoryStock.class);
//  		criteria.add(Restrictions.eq("storeId", storeId));
//  		criteria.add(Restrictions.eq("productBarcode.id", pbId));
//  		
//  		List<HeadQInventoryStock> stocks = this.getByCritera(criteria, true); 
//  		if (stocks.size() > 0)
//  			return stocks.get(0);
//  		else 
//  			return null;
//      }
	
	/**
	 * get the stock number 
	 */
	public int getProductStock(int pbId, int storeId, boolean cache){
		DetachedCriteria criteria = DetachedCriteria.forClass(HeadQInventoryStock.class);
		
		criteria.add(Restrictions.eq("storeId", storeId));
		criteria.add(Restrictions.eq("productBarcode.id", pbId));
		
		criteria.setProjection(Projections.sum("quantity"));
		
		List<Object> result = getByCriteriaProjection(criteria, cache);

        return Common_util.getProjectionSingleValue(result);
	}
	
	
	public Map<Integer, Integer> getProductsInventoryLevel(Set<Integer> pbIds, int storeId) {
		DetachedCriteria criteria = DetachedCriteria.forClass(HeadQInventoryStock.class);
		
		criteria.add(Restrictions.in("productBarcode.id", pbIds));
		criteria.add(Restrictions.eq("storeId", storeId));
		
		ProjectionList projList = Projections.projectionList();
		projList.add(Projections.groupProperty("productBarcode.id"));
		projList.add(Projections.sum("quantity"));
		criteria.setProjection(projList);
		
		List<Object> result = getByCriteriaProjection(criteria, false);
		Map<Integer, Integer> stockMap = new HashMap<Integer, Integer>();
		
		//1. to put the result to stock map
		for (Object object : result)
		  if (object != null){
			Object[] recordResult = (Object[])object;
			int pbId = (Integer)recordResult[0];
			int stock =  (Integer)recordResult[1];
			stockMap.put(pbId, stock);
		  } 

		return stockMap;
	}
	

}
